<template>
  <div>
    <el-dialog v-model="dialog.visible.value" :title="dialog.title.value" width="1300px" append-to-body destroy-on-close>
      <el-card shadow="hover">
        <el-form ref="queryFormRef" :model="queryParams" :inline="true" label-width="90px">
          <el-form-item label="模型名称" >
            <el-input v-model="queryParams.modelName" placeholder="请输入模型名称" clearable @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="() => resetQuery()">重置</el-button>
          </el-form-item>
        </el-form>
      </el-card>

      <el-card shadow="hover" style="height: 500px; margin-top: 6px;">
        <template v-if="prop.multiple" #header>
          <el-tag v-for="device in selectModelList" :key="device.model_id" closable style="margin: 2px" @close="handleCloseTag(device)">
            {{ device.model_name }}
          </el-tag>
        </template>

        <vxe-table
          ref="tableRef"
          height="416px"
          border
          show-overflow
          :data="modelList"
          :loading="modelLoading || selectModelLoading"
          :row-config="{ keyField: 'model_id', isHover: true }"
          :checkbox-config="{ reserve: true, trigger: 'row', highlight: true, showHeader: prop.multiple }"
          @checkbox-all="handleCheckboxAll"
          @checkbox-change="handleCheckboxChange" 
        >
          <vxe-column type="checkbox" width="50" align="center" />
          <vxe-column key="model_name" field="model_name" title="模型名称" align="center" min-width="250px" />
          <vxe-column key="description" field="description" title="描述" align="center" min-width="160px" />
          <vxe-column key="create_time" field="create_time" title="创建时间" align="center" min-width="180px" />
          <vxe-column title="详情" align="center" min-width="500px" >
            <template #default="scope">
              <el-popover effect="light" placement="top" :width="600" trigger="hover" >
                <template #reference>
                  <el-link type="primary" style="overflow: hidden; text-overflow: ellipsis; white-space: nowrap; cursor: pointer; color: blue;" >
                    {{ scope.row.modelDetail }}
                  </el-link>
                </template>
                <template #default>
                  <highlightjs language="json" :code="JSON.stringify(scope.row.modelDetail, null, 2)" style="max-height: 400px; overflow: auto;" />
                </template>
              </el-popover>
            </template>
          </vxe-column>
        </vxe-table>

        <pagination v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" :total="total" @pagination="pageList" />
      </el-card>

      <template #footer>
        <el-button @click="close">取消</el-button>
        <el-button type="primary" @click="confirm">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { UserVO } from '@/api/system/user/types';
import { VxeTableInstance } from 'vxe-table';
import useDialog from '@/hooks/useDialog';
import qs from 'qs'
import request from '@/utils/request';

interface PropType {
  modelValue?: any;
  multiple?: boolean;
  data?: any;
}
const prop = withDefaults(defineProps<PropType>(), {
  multiple: true,
  modelValue: undefined,
  data: undefined
});
const emit = defineEmits(['update:modelValue', 'confirmCallBack']);

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const selectModelList = ref<any[]>([]);
const queryFormRef = ref<ElFormInstance>();
const tableRef = ref<VxeTableInstance<UserVO>>();

const dialog = useDialog({
  title: '物模型选择'
});

const queryParams = ref<any>({
  pageNum: 1,
  pageSize: 10
});

const confirm = () => {
  emit('update:modelValue', selectModelList.value);
  emit('confirmCallBack', selectModelList.value);
  dialog.closeDialog();
};

const computedIdList = (data) => {
  if (data instanceof Array) {
    return [...data];
  } else if (typeof data === 'string') {
    return data.split(',');
  } else if (typeof data === 'number') {
    return [data];
  } 

  return [];
};

/** 查询物模型列表 */
const modelList = ref<any[]>();
const modelLoading = ref(false);
const total = ref(0);
const getList = async () => {
  modelLoading.value = true;
  const res = await request({ url: '/equipment/equipment-product/get-iiot-model-list', method: 'get', params: queryParams.value }).finally(() => { modelLoading.value = false; })
  console.log('获取物模型列表：', res);

  modelList.value = res.data.models;
  total.value = res.data.count;
};

/**
 * 初始化已选物模型
 */
const selectModelLoading = ref(false);
const defaultSelectModelIdList = computed(() => computedIdList(prop.data));
const initSelectDevice = async () => {
  if (defaultSelectModelIdList.value.length > 0) {
    selectModelLoading.value = true;
    let params = qs.stringify({ modelIdList: defaultSelectModelIdList.value }, { arrayFormat: 'repeat', allowDots: true })
    const res = await request({ url: '/equipment/equipment-product/get-iiot-model-list?' + params, method: 'get' }).finally(() => { selectModelLoading.value = false; })
    console.log('初始化已选物模型：', res);

    selectModelList.value = res.data.models;
    const selectedModelList = modelList.value.filter((item) => {
      return defaultSelectModelIdList.value.includes(String(item.model_id));
    });

    // 选中已选设备
    await nextTick(() => {
      tableRef.value.setCheckboxRow(selectedModelList, true);
    });
  }
};

const pageList = async () => {
  await getList();
  const selectedDeviceList = modelList.value.filter((item) => {
    return selectModelList.value.some((user) => user.model_id === item.model_id);
  });
  await tableRef.value.setCheckboxRow(selectedDeviceList, true);
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = (refresh = true) => {
  queryParams.value = { pageNum: 1, pageSize: 10 }
  refresh && handleQuery();
};

const handleCheckboxChange = (checked) => {
  if (!prop.multiple && checked.checked) {
    tableRef.value.setCheckboxRow(selectModelList.value, false);
    selectModelList.value = [];
  }
  const row = checked.row;
  if (checked.checked) {
    selectModelList.value.push(row);
  } else {
    selectModelList.value = selectModelList.value.filter((item) => {
      return item.model_id !== row.model_id;
    });
  }
};
const handleCheckboxAll = (checked) => {
  const rows = modelList.value;
  if (checked.checked) {
    rows.forEach((row) => {
      if (!selectModelList.value.some((item) => item.model_id === row.model_id)) {
        selectModelList.value.push(row);
      }
    });
  } else {
    selectModelList.value = selectModelList.value.filter((item) => {
      return !rows.some((row) => row.model_id === item.model_id);
    });
  }
};

const handleCloseTag = (user: any) => {
  const model_id = user.model_id;
  const index = selectModelList.value.findIndex((item) => item.model_id === model_id);
  const rows = selectModelList.value[index];
  tableRef.value?.setCheckboxRow(rows, false);
  selectModelList.value.splice(index, 1);
};

const close = () => {
  dialog.closeDialog();
};

watch(
  () => dialog.visible.value, async (newValue: boolean) => {
    if (newValue) {
      await getList(); // 初始化列表数据
      await initSelectDevice();
    } else {
      tableRef.value.clearCheckboxReserve();
      tableRef.value.clearCheckboxRow();
      resetQuery(false);
      selectModelList.value = [];
    }
  }
);

defineExpose({
  open: dialog.openDialog,
  close: dialog.closeDialog
});
</script>
<style lang="scss" scoped>
  :deep(.el-dialog) {
    height: 750px !important;
  }
</style>
